<template>
  <div>
    <!-- 图片上传组件辅助-->
    <el-upload
      class="avatar-uploader"
      :action="serverUrl"
      name="image"
      :headers="headers"
      :show-file-list="false"
      list-type="picture"
      :on-exceed="handleExceed"
      :on-error="handleError"
      :on-success="uploadAttachment"
      id="quill-upload"
    >
    </el-upload>
    <!--富文本编辑器组件-->
    <el-row v-loading="quillUpdateImg">
      <quill-editor
        v-model="content"
        ref="myQuillEditor"
        :options="editorOption"
        @change="onEditorChange($event)"
        @ready="onEditorReady($event)"
      >
      </quill-editor>
    </el-row>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import toolbarOptions from "./toolbarOptions";
import { mapGetters, mapState } from "vuex";
import { imgUpload } from "@/api/vadmin/course/course";
import ImageResize from "quill-image-resize-module"; // 引用，调整图片大小
// let fontSize = ['10px', '12px', '14px', '16px', '20px', '24px', '36px', '48px']
// Quill.imports['attributors/style/size'].whitelist = fontSize
Quill.register(Quill.imports["attributors/style/size"]);
Quill.register("modules/imageResize", ImageResize);
export default {
  props: ["data"],

  data() {
    return {
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      serverUrl: "http://123.56.223.128:8080/image/", // 这里写你要上传的图片服务器地址
      // header: { token: "JWT " + getToken() }, // 有的图片服务器要求请求头需要有token之类的参数，写在这里
      xsrfHeaderName: "Authorization", // 请求头的名字自定义，用你们后台给你的就是
      headers: {
        Authorization: "JWT " + getToken(), // 请求头的规则，用你们后台给你的就是
      },
      content: "测试", // 富文本内容
      editorOption: {
        placeholder: "",
        theme: "snow", // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector("#quill-upload input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
          //添加的图片放大缩小 —— 主要地方
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
      }, // 富文本编辑器配置
    };
  },

  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
  },

  watch: {
    data: {
      handler: function (newValue) {
        this.content = newValue;
      },
      immediate: true,
    },
  },

  mounted() {
    //  自定义粘贴图片功能
    let quill = this.$refs.myQuillEditor.quill;
    if (!this.disableFlag) {
      toolbarOptions[0] = ["image"];
    }
    this.$forceUpdate(); //强制刷新
    quill.root.addEventListener(
      "paste",
      (evt) => {
        // console.log("111111>>", evt.clipboardData);
        if (
          evt.clipboardData &&
          evt.clipboardData.files &&
          evt.clipboardData.files.length
        ) {
          evt.preventDefault();
          [].forEach.call(evt.clipboardData.files, (file) => {
            if (!file.type.match(/^image\/(gif|jpe?g|a?png|bmp)/i)) {
              return;
            }
            // console.log("全部", file);
            this.uploadToServer(file, (res) => {
              // 获取光标内容
              // console.log("拿到的结果", file, "222>>>", res);
              var range = quill.getSelection();
              if (range) {
                this.uploadAttachment(res, file, null);
                //  将光标移动到图片后面
                this.$refs.myQuillEditor.quill.setSelection(range.index + 1);
              }
            });
          });
          // console.log(44444, this.content);
        }
      },
      false
    );
  },

  methods: {
    uploadToServer(file, callback) {
      var formData = new FormData();
      formData.append("image", file);

      imgUpload(formData).then((res) => {
        callback(res);
      });
    },
    // 上传图片前
    beforeUpload(res, file) {},
    // 上传图片成功
    uploadSuccess(res, file) {},
    // 上传图片失败
    uploadError(res, file) {},
    onEditorChange({ quill, html, text }) {
      this.content = html;
      this.$emit("dataChange", this.content);
    }, // 内容改变事件
    onEditorReady() {},
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制一次性上传最多 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    handleError(err, file, fileList) {
      this.$message.warning(
        `文件上传失败，请尝试重新上传，文件失败原因为： ${err}`
      );
    },
    uploadAttachment(response, file, fileList) {
      // 保存文件信息
      if (response.id) {
        // 获取富文本组件实例
        let quill = this.$refs.myQuillEditor.quill;
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, "image", response.image);
      } else {
        this.$message.error(response);
      }
      // 清空文件列表
      this.uploadList = [];
    },
  },
};
</script>

